/** @type {HTMLCanvasElement} */

import { randomNum,randomColor } from '../util/index.js'

const canvas = document.querySelector('#canvas')
let width = window.innerWidth
let height = window.innerHeight
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')

const pointNum = 200
const speedBase = 0.7
const lineMax = 100

function Point(x, y,color, dx, dy) {
    this.x = x
    this.y = y
    this.r = 2
    this.color = color
    this.dx = dx
    this.dy = dy

    this.draw = () => {
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
        ctx.fillStyle = this.color
        ctx.fill()
    }

    this.update = () => {
        this.x += this.dx
        this.y += this.dy

        if (this.x - this.r < 0 || this.x + this.r > width) {
            this.dx = -this.dx
        }
        if (this.y - this.r < 0 || this.y + this.r > height) {
            this.dy = -this.dy
        }
        this.draw()
    }
}

function link(point1, point2) {
    const distance = Math.sqrt(Math.pow((point1.x - point2.x), 2) + Math.pow((point1.y - point2.y), 2))
    // console.log(distance);
    if(distance>lineMax)return
    ctx.beginPath()
    ctx.moveTo(point1.x,point1.y)
    ctx.lineTo(point2.x,point2.y)
    ctx.lineWidth = 1
    ctx.strokeStyle = randomColor()
    ctx.stroke()
}

function animate() {
    ctx.clearRect(0, 0, width, height)
    window.requestAnimationFrame(animate)
    pointArr.forEach(p => {
        p.update()
    })
    updateLine()
}

const pointArr = []

function init() {
    for (let i = 0; i < pointNum; i++) {
        const x = randomNum(100, width - 100)
        const y = randomNum(100, height - 100)
        const color = randomColor()
        const dx = randomNum(1, 4) * speedBase
        const dy = randomNum(1, 4) * speedBase
        const point = new Point(x, y, color,dx, dy)
        pointArr.push(point)
        point.draw()
    }
}

function updateLine(){
    const len = pointArr.length
    for(let i=0;i<len;i++){
        for(let j=i+1;j<len;j++){
            link(pointArr[i],pointArr[j])
        }
    }
}
init()
animate()